package cn.helele.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@Slf4j
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        /**
         * pre 请求在被路由之前执行
         * 登录校验，肯定是在前置拦截
         */
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        // 过滤器的执行顺序，值越小越先被执行
        return FilterConstants.PRE_DECORATION_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        // 返回true表示过滤器生效
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 登录校验逻辑
        // 1)获取zuul提供的请求上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 2)通过上下文对象获取servletrequest对象
        HttpServletRequest request = requestContext.getRequest();

        String token = request.getParameter("token");
        if (token == null || "".equals(token.trim())) {
            // 没有token,登录校验失败,拦截
            requestContext.setSendZuulResponse(false);
            // 返回401状态码，也可以考虑重定向到登录页
            requestContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            // 响应内容,这里如果写中文，会乱码，待解决
            requestContext.setResponseBody("not authorization");
            log.info("未授权的请求!");
        }
        return null;
    }
}
